package com.huatai.datacenter.controller.fire.retention;

import com.huatai.datacenter.entity.ApiEntity;
import com.huatai.datacenter.service.ApiService;
import com.huatai.dataservice.fire.feign.FireClient;
import com.huatai.dataservice.fire.firemodel.ResponseVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author gaowengui
 * @Description //切面类实现类
 * @Date 15:51 2025/6/23
 * @Param
 * @return
 **/
@Aspect
@Component
public class ApiCheckAspect {

    @Autowired
    private ApiService apiService;

    @Autowired
    private FireClient fireClient;

    /**
     * @Author gaowengui
     * @Decription 检查方法上是否有该注解
     **/
    @Around("@annotation(apiCheck)")
    public Object checkApi(ProceedingJoinPoint joinPoint, ApiCheck apiCheck) throws Throwable {
        // 获取请求上下文
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return joinPoint.proceed(); // 非web请求直接放行
        }

        HttpServletRequest request = attributes.getRequest();
        String requestURI = request.getRequestURI();
        String processedURI = processUri(requestURI);

        // 检查API配置
        if (!isApiDisabled(processedURI)) {
            return new ResponseVo();
        }
        // 执行原始方法
        return joinPoint.proceed();
    }

    /**
     * @return a
     * @Author gaowengui
     * @Decription //TODO a
     * @Date 15:53 2025/6/3
     * @Param
     **/
    private String processUri(String requestUri) {
        if (requestUri == null || requestUri.isEmpty()) {
            return "";
        }
        return requestUri.startsWith("/") ? requestUri.substring(1) : requestUri;
    }

    /**
     * @return a
     * @Author gaowengui
     * @Decription //TODO a
     * @Date 15:53 2025/6/3
     * @Param
     **/
    private boolean isApiDisabled(String processedUri) {
        List<ApiEntity> config = apiService.getConfigList(processedUri);
        if (config == null || config.isEmpty()) {
            return false;
        }
        return true;
    }
}